﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PBKVideo;

namespace PBKApplication
{
    public partial class FormDownload : Form
    {
        private Video curVideo;
        private List<VideoQuality> ls;
        private SearchBar searchBar;

        public FormDownload(List<VideoQuality> ls, Video vid, SearchBar sc)
        {
            InitializeComponent();
            pictureThumb.LoadAsync(vid.UrlThumbnail);
            this.ls = ls;
            curVideo = vid;
            searchBar = sc;
            searchBar.DownloadProgressChanged += new ProgressChangedEventHandler(searchBar1_DownloadProgressChanged);
            searchBar.DownloadCompleted += new RunWorkerCompletedEventHandler(searchBar1_DownloadCompleted);
            lblTitle.Text = vid.Title;
            comboVideos.DataSource = ls;
        }

        private string FormatTitle(string title)
        {
            return title.Replace(@"\", "").Replace("&#39;", "'").Replace("&quot;", "'").Replace("&lt;", "(").Replace("&gt;", ")").Replace("+", " ").Replace(":", "-").Replace(@"/",@"");
        }

        private void FormDownload_FormClosing(object sender, FormClosingEventArgs e)
        {
            searchBar.AbortDownload();
            this.Dispose(true);
        }

        private void extractVideoURLCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            statusLabel.Text = @"Refreshing done.";
            btnStartPause.Enabled = btnStop.Enabled = true;
            List<VideoQuality> ls = e.Result as List<VideoQuality>;
            comboVideos.DataSource = ls;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            btnStartPause.Enabled = btnStop.Enabled = false;
            searchBar.ExtractVideoURLCompleted -= extractVideoURLCompleted;
            searchBar.ExtractVideoURLCompleted += new RunWorkerCompletedEventHandler(extractVideoURLCompleted);
            statusLabel.Text = @"Refreshing list videos...";
            searchBar.ExtractVideoURLs(curVideo);
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            VideoQuality vid = comboVideos.SelectedItem as VideoQuality;
            if (vid != null)
            {
                saveFileDialog1.Filter = String.Format("{0} Files|*.{1}", vid.Extension.ToUpper(), vid.Extension.ToLower());
                saveFileDialog1.FileName = FormatTitle(curVideo.Title);
                if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
                {
                    textSaveTo.Text = saveFileDialog1.FileName;
                }
            }
        }

        private bool processing = false;
        private void searchBar1_DownloadProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (processing)
            {
                return;
            }
            if (InvokeRequired)
            {
                Invoke(new ProgressChangedEventHandler(searchBar1_DownloadProgressChanged), sender, e);
            }
            else
            {
                try
                {
                    processing = true;
                    progressBar1.Value = e.ProgressPercentage > 100 ? 100 : e.ProgressPercentage;
                    this.Text = "Download - " + e.ProgressPercentage + " %";
                    string speed = String.Format(@"{0:F2}",searchBar.DownloadSpeed / 1024.0);
                    string ETA = searchBar.ETA.ToString();
                    lblSpeed.Text = speed;
                    lblRemaining.Text = ETA;
                }
                catch { }
                finally
                {
                    processing = false;
                }
            }
        }

        private void searchBar1_DownloadCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled)
            {
                this.Close();
            }
            else
            {
                switch (searchBar.DownloadStatus)
                {
                    case DownloadStatus.Success:
                        statusLabel.Text = @"Download completed.";
                        btnStop.Enabled = false;
                        btnStartPause.Enabled = false;
                        break;
                    case DownloadStatus.Failed:
                        statusLabel.Text = @"Download failed. - " + e.Error.Message;
                        btnStartPause.Text = @"Start";
                        break;
                    case DownloadStatus.Canceled:
                        statusLabel.Text = @"Cancelling...";
                        break;
                }
            }
        }

        private void btnStartPause_Click(object sender, EventArgs e)
        {
            VideoQuality vid = comboVideos.SelectedItem as VideoQuality;
            if (vid == null)
            {
                return;
            }
            if (btnStartPause.Text == @"Start")
            {
                panelVideo.Enabled = false;
                btnBrowse.Enabled = false;
                btnStartPause.Text = @"Pause";
                searchBar.DownloadVideo(vid.DownloadURL,textSaveTo.Text);
                statusLabel.Text = @"Downloading...";
            }
            else
                if (btnStartPause.Text == @"Resume")
                {
                    btnStartPause.Text = @"Pause";
                    statusLabel.Text = @"Downloading...";
                    searchBar.ResumeDownload();
                }
                else
                    if (btnStartPause.Text == @"Pause")
                    {
                        btnStartPause.Text = @"Resume";
                        statusLabel.Text = @"Paused.";
                        searchBar.PauseDownload();
                    }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            btnStartPause.Enabled = false;
            btnStop.Enabled = false;
            searchBar.CancelDownloadAsync();
        }
    }
}
